package mju.cxf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import mju.cxf.context.BaseContext;
import mju.cxf.entity.*;
import mju.cxf.mapper.SalesAfterMapper;
import mju.cxf.service.*;
import mju.cxf.vo.SalesAfterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 售后表 服务实现类
 * </p>
 *
 * @author 郑献
 * @since 2024-10-30
 */

@Service
public class SalesAfterServiceImpl extends ServiceImpl<SalesAfterMapper, SalesAfter> implements SalesAfterService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private SalesServiceImpl salesServiceImpl;
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private IntegralServiceImpl integralServiceImpl;
    @Autowired
    private BillService billService;
    @Autowired
    private ProductSpecificationsService productSpecificationsService;
    /**
     * A分页查询售后信息
     *
     * @param number
     * @return
     */
    @Override
    public Page<SalesAfterVO> selectPage(String number, Integer status, int current, int size) {
        Page<SalesAfterVO> page = new Page<>(current, size);
        return this.baseMapper.selectPageVo(page, number, status);
    }


    @Override
    @Transactional
    public boolean updateSalesAfter(SalesAfter salesAfter) {
        //获取有争议出售商品
        LambdaQueryWrapper<Sales> sqw = new LambdaQueryWrapper<>();
        sqw.eq(Sales::getOrderNumber, salesAfter.getOrderNumber()).eq(Sales::getState, 5);
        final List<Sales> salesList = salesServiceImpl.list(sqw);
        //订单状态修改支付
        Order order = orderService.sleectOrderNumber(salesAfter.getOrderNumber());
        order.setStatus(1);
        orderService.updateById(order);
        if (salesAfter.getStatus() == 1) {
            //纠纷成功执行操作
            for (Sales sales : salesList) {
                /*
                 * 扣除卖家信用分
                 */
                final User user = userServiceImpl.getById(sales.getUserId());
                if (user.getCredit()!=0){
                    Integral integral = new Integral();
                    integral.setUserId(sales.getUserId()); //获取用户id
                    integral.setCreateTime(LocalDateTime.now()); //设置创建时间
                    integral.setTittle("出售商品无法使用");
                    integral.setType(3); //设置为减少信用分
                    integral.setNumber(user.getCredit() >= 5 ?5 : user.getCredit());//分值
                    integralServiceImpl.save(integral); //插入数据库
                }
                //扣除买家冻结资金
                LambdaUpdateWrapper<User> uuw1 = new LambdaUpdateWrapper<>();
                uuw1.eq(User::getId, sales.getUserId()).set(User::getCredit, user.getCredit() >= 5?user.getCredit()-5 : 0).
                        set(User::getFreezeBalances, user.getFreezeBalances() - sales.getAmount());
                userServiceImpl.update(uuw1);
                //卖家金钱 账单
                Bill bill = Bill.builder()
                        .topic("订单纠纷收回")
                        .type(2)
                        .balancesType(1)
                        .createTime(LocalDateTime.now())

                        .number(sales.getAmount())
                        .userId(sales.getUserId())
                        .build();
                billService.save(bill);
                /*
                出售商品设为取消
                 */
                sales.setState(7);//旧商品设置为已被退款
            }
            salesServiceImpl.updateBatchById(salesList);

             /*
             买家退订单钱
             */
            // 日你妈 退钱
            double pri= order.getIntegralPrice();
            LambdaUpdateWrapper<User> uuw = new LambdaUpdateWrapper<>();
            //退回积分
            if (pri>0){
                Integral integral = new Integral();
                integral.setUserId(order.getUserId()); //获取用户id
                integral.setCreateTime(LocalDateTime.now()); //设置创建时间
                integral.setTittle("售后退回积分");
                integral.setType(1); //设置为减少信用分
                integral.setNumber((int) (order.getIntegralPrice()*1000 /order.getQuantity()));//分值
                integralServiceImpl.save(integral); //插入数据库
            }
            System.out.println(salesList.size());
            uuw.eq(User::getId, order.getUserId()).setSql("available_balance = available_balance + " + (order.getAmount()/order.getQuantity())*salesList.size())
                    .setSql("points=points+"+(int)(order.getIntegralPrice()*1000 /order.getQuantity()));
            //入账
            Bill bill = Bill.builder()
                    .topic("订单退款")
                    .type(1)
                    .balancesType(2)
                    .createTime(LocalDateTime.now())
                    .number((order.getAmount()/order.getQuantity())*salesList.size())
                    .userId(order.getUserId())
                    .build();
            billService.save(bill);
            userServiceImpl.update(uuw);
            orderService.updateById(order);
        } else {
            //纠纷失败执行操作
            for (Sales sales : salesList) {
                sales.setState(4);//商品回到出售中
            }
        }
        salesAfter.setProcessingTime(LocalDateTime.now());//处理时间
        return this.updateById(salesAfter);
    }
}
